package cm.lock.redis;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * LOCK 锁 ReentrantLock
 */
public class RedisLockTest {
    private static Integer Inventry = 1001;
    private  static final  int NUM = 1000;
    private static LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue();
    static ReentrantLock reentrantLock = new ReentrantLock();
//    static RedisLock redisLock = new RedisLock();

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(Inventry,Inventry,10L, TimeUnit.SECONDS,linkedBlockingQueue);
        final CountDownLatch countDownLatch = new CountDownLatch(NUM);
        long start = System.currentTimeMillis();
        for (int i = 0;i <= NUM;i++){
            threadPoolExecutor.execute(new Runnable() {
                public void run() {
//                    reentrantLock.lock();//Lock
                    String uuid = UUID.randomUUID().toString();
//                    redisLock.lock(UUID.randomUUID().toString());
                    Inventry--;
//                    redisLock.unlock(UUID.randomUUID().toString());
//                    reentrantLock.unlock();//Lock
                    System.out.println("线程执行;{}"+Thread.currentThread().getName());
                    countDownLatch.countDown();
                }
            });
        }
        threadPoolExecutor.shutdown();
        try{
            countDownLatch.await();
        }catch (Exception e){
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("执行线程：{}"+NUM+"总耗时"+(end-start)+"库存：{}"+Inventry);
    }

}
